// 移动端菜单切换
document.getElementById('mobileMenuBtn').addEventListener('click', function() {
    const mobileMenu = document.getElementById('mobileMenu');
    mobileMenu.classList.toggle('hidden');
});

// 页面滚动时导航栏效果
window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (window.scrollY > 10) {
        header.classList.add('shadow-md');
        header.classList.remove('nav-shadow');
    } else {
        header.classList.remove('shadow-md');
        header.classList.add('nav-shadow');
    }
});

// 平滑滚动
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        const targetId = this.getAttribute('href');
        const targetElement = document.querySelector(targetId);

        if (targetElement) {
            window.scrollTo({
                top: targetElement.offsetTop - 80,
                behavior: 'smooth'
            });

            // 如果是移动端，点击后关闭菜单
            const mobileMenu = document.getElementById('mobileMenu');
            if (!mobileMenu.classList.contains('hidden')) {
                mobileMenu.classList.add('hidden');
            }
        }
    });
});

// 进度条动画
document.addEventListener('DOMContentLoaded', function() {
    const progressBars = document.querySelectorAll('[data-width]');
    progressBars.forEach(bar => {
        const width = bar.getAttribute('data-width');
        setTimeout(() => {
            bar.style.width = width;
        }, 100);
    });

    // 初始化空图表
    initNetValueChart();
    initMonthlyReturnChart();
});

// 从服务端获取仪表盘数据
async function fetchDashboardData(taskId = null) {
    try {
        // 构建请求URL，匹配后端API路径
        let url = '/api/chart/dashboard';
        if (taskId) {
            url += `?taskId=${encodeURIComponent(taskId)}`;
        }

        // 发送请求
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP错误状态: ${response.status}`);
        }

        return await response.json();
    } catch (error) {
        console.error('获取仪表盘数据失败:', error);
        alert('获取数据失败，请重试');
        return null;
    }
}

// 净值曲线图表 - 初始化空图表
function initNetValueChart() {
    const ctx = document.getElementById('netValueChart').getContext('2d');

    // 销毁已存在的图表实例
    if (window.netValueChartInstance) {
        window.netValueChartInstance.destroy();
    }

    // 创建空图表
    window.netValueChartInstance = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: []
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(29, 33, 41, 0.9)',
                    padding: 10,
                    cornerRadius: 6
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: false,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return value.toFixed(2);
                        }
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            },
            animation: {
                duration: 1500,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 渲染净值曲线图表
function renderNetValueChart(data) {
    // 准备图表数据
    const labels = data.map(item => item.date);
    const netValues = data.map(item => item.value);

    // 销毁已存在的图表
    if (window.netValueChartInstance) {
        window.netValueChartInstance.destroy();
    }

    const ctx = document.getElementById('netValueChart').getContext('2d');
    window.netValueChartInstance = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '策略净值',
                data: netValues,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22, 93, 255, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.3,
                pointBackgroundColor: '#165DFF',
                pointRadius: 3,
                pointHoverRadius: 5
            }]
        },
        options: window.netValueChartInstance.options // 复用之前的配置
    });
}

// 月度收益图表 - 初始化空图表
function initMonthlyReturnChart() {
    const ctx = document.getElementById('monthlyReturnChart').getContext('2d');

    // 销毁已存在的图表实例
    if (window.monthlyReturnChartInstance) {
        window.monthlyReturnChartInstance.destroy();
    }

    // 创建空图表
    window.monthlyReturnChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: [],
            datasets: []
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(29, 33, 41, 0.9)',
                    padding: 10,
                    cornerRadius: 6,
                    callbacks: {
                        label: function(context) {
                            const value = context.raw;
                            return `收益: ${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return value >= 0 ? '+' + value + '%' : value + '%';
                        }
                    }
                }
            },
            animation: {
                duration: 1500,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 渲染月度收益图表
function renderMonthlyReturnChart(data) {
    // 准备图表数据
    const labels = data.map(item => item.month);
    const returns = data.map(item => item.returnRate);

    // 为正负收益设置不同颜色
    const backgroundColors = returns.map(value =>
        value >= 0 ? 'rgba(82, 196, 26, 0.7)' : 'rgba(245, 34, 45, 0.7)'
    );

    // 销毁已存在的图表
    if (window.monthlyReturnChartInstance) {
        window.monthlyReturnChartInstance.destroy();
    }

    const ctx = document.getElementById('monthlyReturnChart').getContext('2d');
    window.monthlyReturnChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '月度收益(%)',
                data: returns,
                backgroundColor: backgroundColors,
                borderWidth: 0,
                borderRadius: 4,
                barPercentage: 0.6,
                categoryPercentage: 0.7
            }]
        },
        options: window.monthlyReturnChartInstance.options // 复用之前的配置
    });
}

// 渲染仪表盘数据
function renderDashboard(data) {
    // 更新核心指标卡片
    $('h3:contains("总收益率")').siblings().first().text(data.totalReturnRate.toFixed(2) + '%');
    $('h3:contains("年化收益率")').siblings().first().text(data.yearsReturnRate.toFixed(2) + '%');
    $('h3:contains("夏普比率")').siblings().first().text(data.sharpeRatio.toFixed(2));
    $('h3:contains("最大回撤")').siblings().first().text(data.maxDrawdown.toFixed(2) + '%');

    // 更新交易统计
    $('span:contains("总交易次数")').parent().find('.font-medium').text(data.totalTrades);
    $('span:contains("胜率")').parent().find('.font-medium').text(data.winRate.toFixed(1) + '%');
    $('span:contains("平均持股天数")').parent().find('.font-medium').text(data.avgHoldDays.toFixed(1) + '天');
    $('span:contains("盈亏比")').parent().find('.font-medium').text(data.ProfitLossRatio);

    // 更新进度条
    $('[data-width="78%"]').css('width', (data.totalTrades > 0 ? Math.min(100, data.totalTrades / 2) : 0) + '%');
    $('[data-width="62.3%"]').css('width', data.winRate + '%');

    // 渲染净值曲线图表
    if (data.netValueCurve) {
        renderNetValueChart(data.netValueCurve);
    }

    // 计算并渲染月度收益图表数据
    if (data.netValueCurve && data.netValueCurve.length > 0) {
        const monthlyReturns = calculateMonthlyReturns(data.netValueCurve);
        renderMonthlyReturnChart(monthlyReturns);
    }
}

// 根据净值曲线计算月度收益率
function calculateMonthlyReturns(netValueCurve) {
    const monthlyData = {};

    // 按月份分组
    netValueCurve.forEach(point => {
        const date = new Date(point.date);
        const yearMonth = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;

        if (!monthlyData[yearMonth]) {
            monthlyData[yearMonth] = {
                first: point.value,
                last: point.value
            };
        } else {
            monthlyData[yearMonth].last = point.value;
        }
    });

    // 计算月度收益率
    const result = [];
    let previousValue = null;

    Object.keys(monthlyData).sort().forEach(month => {
        const data = monthlyData[month];
        if (previousValue) {
            const returnRate = ((data.last - previousValue) / previousValue) * 100;
            result.push({
                month: month,
                returnRate: returnRate
            });
        }
        previousValue = data.last;
    });

    return result;
}

// 等待页面DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有导航链接
    const navLinks = document.querySelectorAll('nav a');

    // 为每个导航链接添加点击事件监听器
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            // 移除所有导航链接的高亮样式
            navLinks.forEach(item => {
                item.classList.remove('text-primary', 'font-medium', 'border-b-2', 'border-primary');
                item.classList.add('text-dark-2', 'hover:text-primary');
            });

            // 为当前点击的导航链接添加高亮样式
            this.classList.remove('text-dark-2', 'hover:text-primary');
            this.classList.add('text-primary', 'font-medium', 'border-b-2', 'border-primary');
        });
    });
});

// 收集回测参数并发送请求
async function startBacktest() {
    // 收集股票池数据
    const stockElements = document.querySelectorAll('.flex-wrap.gap-2 span');
    const stockPool = Array.from(stockElements).map(el => {
        const text = el.textContent.trim();
        const [name, code] = text.split('(');
        return {
            name: name.trim(),
            code: code.replace(')', '').trim()
        };
    });

    // 收集时间范围
    const startDate = document.querySelector('input[type="date"]:first-of-type').value;
    const endDate = document.querySelector('input[type="date"]:last-of-type').value;

    // 收集资金参数
    const initialCapital = parseFloat(document.querySelector('input[value="1000000"]').value);

    // 收集交易成本参数
    const commissionRate = parseFloat(document.querySelector('input[value="0.03"]').value);
    const minCommission = parseFloat(document.querySelector('input[value="5"]').value);
    const stampDutyRate = parseFloat(document.querySelector('input[value="0.1"]').value);

    // 收集仓位管理参数
    const maxPositionPerStock = parseFloat(document.querySelector('input[value="20"]').value);

    // 收集策略参数
    const strategyParams = {
        shortTermMA: parseInt(document.querySelector('input[value="10"]').value),
        longTermMA: parseInt(document.querySelector('input[value="30"]').value),
        rsiOverbought: parseInt(document.querySelector('input[value="75"]').value),
        rsiOversold: parseInt(document.querySelector('input[value="25"]').value)
    };

    // 构建请求数据
    const requestData = {
        stockPool,
        timeRange: {
            startDate,
            endDate
        },
        initialCapital,
        transactionCost: {
            commissionRate,
            minCommission,
            stampDutyRate
        },
        positionManagement: {
            maxPositionPerStock
        },
        strategyParams
    };

    try {
        // 发送回测请求
        const response = await fetch('/api/backtest/start', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token') // 如果需要认证
            },
            body: JSON.stringify(requestData)
        });

        if (!response.ok) {
            throw new Error('回测请求失败');
        }

        const result = await response.json();

        // 处理成功响应，比如跳转到结果页面
        if (result.success) {
            alert('回测已开始，任务ID: ' + result.taskId);
            // 跳转到结果页面，使用任务ID查询进度
            window.location.href = `/results?taskId=${result.taskId}`;
        }
    } catch (error) {
        console.error('回测请求错误:', error);
        alert('回测启动失败: ' + error.message);
    }
}

// 导出数据功能
document.querySelector('button:has(.fa-download)').addEventListener('click', async function() {
    const dashboardData = await fetchDashboardData();
    if (dashboardData) {
        // 构建导出数据
        const exportData = {
            策略名称: "量化策略",
            总收益率: `${dashboardData.totalReturnRate.toFixed(2)}%`,
            年化收益率: `${dashboardData.yearsReturnRate.toFixed(2)}%`,
            夏普比率: dashboardData.sharpeRatio.toFixed(2),
            最大回撤: `${dashboardData.maxDrawdown.toFixed(2)}%`,
            总交易次数: dashboardData.totalTrades,
            胜率: `${dashboardData.winRate.toFixed(1)}%`,
            平均持股天数: `${dashboardData.avgHoldDays.toFixed(1)}天`,
            盈亏比: dashboardData.ProfitLossRatio,
            净值曲线: dashboardData.netValueCurve
        };

        // 转换为JSON并下载
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `策略回测结果_${new Date().toLocaleDateString()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
});
